/* eslint-disable react/no-array-index-key */
/**
 * 需求简历，详情页 -- 人才库
 */
import React from 'react';
import { history } from 'umi'
import { PageContainer } from '@/molecules';
import { useRequest, defaultFormatResult } from '@/hooks';
import { Tabs, Row, Spin, Icon } from 'antd';
import helper from '@/utils/auth/helper';
import { connect } from 'umi';
import { useRenderDuty } from '@/pages/Recruitment/hooks';
import styles from './Detail.less';
import { TalentInfoHead, Operates } from '../components';
import { RESUME_LABEL_ENUM, RECOMMEND_TYPE_VALUES } from '../dictionary';
import {
    TalentsBlackListOperate,
    TalentsJoinSeniorOperate,
    RecommendOperate,
    TalentStatusStep,
    ResumeDetail,
    InterviewCard
} from '../containers';
import HireDetail from '../Hire/HireDetail/HireDetail';
import { getResumesDetail, queryTalentDuties, queryInterviewDetailList } from '../service';
import TalentDetailContext from '../TalentDetailContext';

const { checkCode } = helper;

const TalentDetail = ({ location, user }) => {
    const { query } = location;
    const { currentUser = {} } = user;
    const [stepShow, setStepShow] = React.useState(true);
    // const [currDuty, setCurrDuty] = React.useState();
    const { talentCode, activeKey } = query;
    const hireDetailRef = React.useRef();
    // 人才库信息
    const { data: talentDutyInfo, loading: talentDutyInfoLoading, run: runTalentDutyInfo } = useRequest(
        () => queryTalentDuties(talentCode),
        { ...defaultFormatResult }
    );

    // 获取简历ID
    const resumeId = React.useMemo(() => {
        if (query.currResumeId) {
            return parseInt(query.currResumeId, 10);
        }
        const dutyList = talentDutyInfo?.dutyList;
        if (dutyList && dutyList.length) {
            return dutyList[0].resumeId;
        }
        return undefined;
    }, [query.currResumeId, talentDutyInfo]);

    // 人才信息
    const { data, run, loading } = useRequest(() => getResumesDetail(resumeId), {
        manual: true,
        ...defaultFormatResult
    });

    const talentInfo = React.useMemo(() => {
        if (!resumeId || !data) {
            return undefined;
        }
        return { ...data, id: resumeId, origin: 'talent', hasBlackList: talentDutyInfo?.hasBlackList };
    }, [data, resumeId, talentDutyInfo]);

    // 获取人才信息
    React.useEffect(() => {
        if (resumeId) {
            run();
        }
    }, [resumeId]);

    // 岗位权限
    const auth = React.useMemo(() => {
        const hasRecruitAuth = talentInfo?.hasRecruitAuth ?? true; // 当前用户是否有查看 面试、录用等阶段的权限
        return {
            RESUME: checkCode('office:recruitment:course:resume'), // 简历
            INTERVIEW: checkCode('office:recruitment:course:interview') && hasRecruitAuth, // 面试
            HIRE: checkCode('office:recruitment:course:hire') && hasRecruitAuth // 录用
        };
    }, [talentInfo?.hasRecruitAuth]);
    const tabActiveKey = React.useMemo(() => {
        if (!activeKey) {
            return Object.keys(auth).find(key => auth[key]);
        }
        return activeKey;
    }, [activeKey]);

    const handleTabChange = key => {
        history.push({
            query: {
                ...query,
                activeKey: key
            }
        });
    };
    const [refreshComponents, setRefreshComponents] = React.useState([]);
    // 设置哪些模块需刷新
    const pushRefreshComponents = React.useCallback(comps => {
        setRefreshComponents(arr => arr.concat(comps));
    }, []);

    // 移除徐刷新的
    const removeRefreshedComponent = React.useCallback(comp => {
        setRefreshComponents(arr => arr.filter(item => item !== comp));
    }, []);

    // 判断模块是否需要刷新
    const getRefreshByKey = React.useCallback(key => refreshComponents.findIndex(com => com === key) !== -1, [
        refreshComponents
    ]);

    // 当前登录人是否为招聘负责人
    const principalFlag = React.useMemo(() => talentInfo?.principalEmployeeCode === currentUser?.employeeCode, [
        talentInfo?.principalEmployeeCode,
        currentUser?.employeeCode
    ]);
    // 当前登录人是否为招聘发起人
    const launcherFlag = React.useMemo(() => talentInfo?.launchEmployeeCode === currentUser?.employeeCode, [
        talentInfo?.launchEmployeeCode,
        currentUser?.employeeCode
    ]);
    // 验证是否为面试官
    const isInterviewer = React.useCallback(
        (employeeArr = []) => employeeArr.some(item => item?.employeeCode === currentUser?.employeeCode),
        [currentUser?.employeeCode]
    );

    // 面试详情列表
    const { data: interviewDetailList = [], run: runInterviewDetailList } = useRequest(
        () => {
            if (talentInfo?.candidateId) return queryInterviewDetailList(talentInfo?.candidateId);
            return Promise.resolve({ code: 10000, data: [] });
        },
        {
            refreshDeps: [talentInfo?.candidateId],
            ...defaultFormatResult
        }
    );
    // 刷新数据
    React.useEffect(() => {
        if (getRefreshByKey('TalentDutyInfo')) {
            runTalentDutyInfo();
            removeRefreshedComponent('TalentDutyInfo');
        }
        if (getRefreshByKey('InterviewDetailList')) {
            runInterviewDetailList();
            removeRefreshedComponent('InterviewDetailList');
        }
        if (getRefreshByKey('HireDetail')) {
            if (hireDetailRef?.current) {
                hireDetailRef.current.runHireDetail();
                removeRefreshedComponent('HireDetail');
            }
        }
    }, [refreshComponents]);

    const renderDuties = useRenderDuty({ talentDutyInfo, resumeId, query });

    // 面试页签
    const interviewTab = React.useMemo(() => {
        const resumeStep = talentInfo?.resumeStep;
        if (resumeStep === 1 || !talentInfo?.candidateId || !interviewDetailList.length) {
            return '';
        }
        return (
            <Tabs.TabPane tab={`面试(${interviewDetailList.length})`} key="INTERVIEW">
                {interviewDetailList.map((item, index) => (
                    // id：锚点。操作步骤那边需要跳转至对应的面试记录
                    <div id={`INTERVIEW_DETAIL-${item?.contactRecordDetailVO?.id}`} key={index}>
                        <InterviewCard
                            data={item}
                            candidateId={talentInfo?.candidateId}
                            resumeId={resumeId}
                            principalFlag={principalFlag}
                            launcherFlag={launcherFlag}
                            interviewerFlag={isInterviewer(item?.arrangeDetailVO?.interviewEmployees)}
                        />
                        {index !== interviewDetailList.length - 1 && <div style={{ marginBottom: 20 }}></div>}
                    </div>
                ))}
            </Tabs.TabPane>
        );
    }, [interviewDetailList, talentInfo?.candidateId, talentInfo?.resumeStep]);

    // 录用页签
    const hireTab = React.useMemo(() => {
        const resumeStep = talentInfo?.resumeStep;
        if (resumeStep < 4) {
            return null;
        }
        return (
            <Tabs.TabPane tab="录用" key="HIRE">
                <HireDetail
                    employId={talentInfo?.employId}
                    candidateId={talentInfo?.candidateId}
                    hireDetailRef={hireDetailRef}
                />
            </Tabs.TabPane>
        );
    }, [talentInfo?.resumeStep, talentInfo?.employId]);
    const renderBtn = React.useCallback(() => {
        if (!talentDutyInfo) {
            return null;
        }
        const { dutyNum, dutyList = [] } = talentDutyInfo;
        const { recruitList = [] } = talentInfo || {};
        // 无匹配岗位 或者 当前岗位已淘汰、已取消
        const recommendType =
            dutyNum === 0 ||
            [RESUME_LABEL_ENUM.CANCELED, RESUME_LABEL_ENUM.OBSOLETE].includes(
                dutyList.find(duty => duty?.resumeId === resumeId)?.resumeLabel
            )
                ? RECOMMEND_TYPE_VALUES.COMMON
                : RECOMMEND_TYPE_VALUES.OTHER;
        const recommend = !talentDutyInfo?.hasBlackList && (
            <RecommendOperate
                resumeId={resumeId}
                onConfirm={() => pushRefreshComponents(['TalentStatusStep', 'InterviewDetailList', 'HireDetail'])}
                type={recommendType}
                weedOutDisabled={!(principalFlag || launcherFlag)}
                talentCode={talentCode}
                showSelect={false}
            />
        );

        const defaultNoticeEmployee = new Set();
        recruitList.forEach(item => {
            defaultNoticeEmployee.add(item.launchEmployeeCode);
            defaultNoticeEmployee.add(item.principalEmployeeCode);
        });
        // 加入/移出黑名单
        let messageType = 0; // 黑名单提示语类型
        const { resumeLabel } = dutyList?.find(v => v.resumeId === Number(resumeId)) || {};
        if (![2, 3].includes(resumeLabel)) {
            // 提示类型1：应聘中：【面试】【录用】阶段
            if ([3, 4].includes(talentInfo?.resumeStep) && resumeLabel === 1) messageType = 1;
            // 提示类型2：【简历】【候选】阶段
            if ([1, 2].includes(talentInfo?.resumeStep)) messageType = 2;
        }
        const moveToBlack = (
            <TalentsBlackListOperate
                talentCode={talentCode}
                operateType={talentDutyInfo?.hasBlackList ? 'remove' : 'add'}
                onRefresh={() =>
                    pushRefreshComponents(['TalentDutyInfo', 'TalentStatusStep', 'InterviewDetailList', 'HireDetail'])
                }
                defaultNoticeEmployee={Array.from(defaultNoticeEmployee)}
                resumeStep={talentInfo?.resumeStep}
                messageType={messageType}
            />
        );
        const moveToSenior = talentDutyInfo?.hasMatchAdvance && !talentDutyInfo?.hasBlackList && (
            <TalentsJoinSeniorOperate
                talentCode={talentCode}
                operateType={talentDutyInfo?.hasAdvance ? 'remove' : 'add'}
                onRefresh={() => pushRefreshComponents(['TalentDutyInfo', 'TalentStatusStep'])}
                defaultNoticeEmployee={Array.from(
                    new Set([talentInfo?.launchEmployeeCode, talentInfo?.principalEmployeeCode])
                )}
            />
        );

        return <Operates operates={[recommend, moveToBlack, moveToSenior]} spaceSplit />;
    }, [talentDutyInfo, talentInfo, resumeId]);

    const renderSpin = React.useCallback(
        () => (
            <Row type="flex" justify="center" style={{ padding: 32 }}>
                <Spin />
            </Row>
        ),
        []
    );

    if (talentDutyInfoLoading) {
        return renderSpin();
    }

    return (
        <TalentDetailContext.Provider value={talentInfo}>
            <PageContainer>
                <div style={{ margin: 16 }}>
                    {/* 头部 */}
                    <Row type="flex" justify="space-between" align="top" style={{ marginBottom: 24 }}>
                        <TalentInfoHead talent={talentInfo} dutyCom={renderDuties()} />
                        {renderBtn()}
                    </Row>
                    <Row type="flex" style={{ marginTop: '20' }}>
                        <Tabs
                            type="card"
                            className={styles.cardTabs}
                            activeKey={tabActiveKey}
                            onChange={handleTabChange}
                            style={{ flex: 1 }}
                        >
                            {auth.RESUME && (
                                <Tabs.TabPane tab="简历信息" key="RESUME">
                                    {loading ? renderSpin() : <ResumeDetail />}
                                </Tabs.TabPane>
                            )}
                            {auth.INTERVIEW && interviewTab}
                            {auth.HIRE && hireTab}
                        </Tabs>
                        <div
                            style={{
                                position: 'relative',
                                marginTop: 39,
                                width: stepShow ? 64 : 33,
                                borderTop: '1px solid rgb(232, 232, 232)'
                            }}
                        >
                            <div
                                style={{
                                    position: 'absolute',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    zIndex: 1000,
                                    top: 100,
                                    left: 11,
                                    width: 22,
                                    height: 36,
                                    cursor: 'pointer',
                                    background: '#FFFFFF',
                                    boxShadow: '-4px 0px 8px 0px rgba(0, 0, 0, 0.06)',
                                    borderRadius: '4px 0px 0px 4px',
                                    border: '1px solid #EEEEEE',
                                    borderRight: 0
                                }}
                                onClick={() => setStepShow(val => !val)}
                            >
                                <Icon type={stepShow ? 'right' : 'left'} />
                            </div>
                            <div
                                style={{
                                    marginLeft: 32,
                                    borderLeft: '1px solid rgb(232, 232, 232)',
                                    width: 0,
                                    height: '100%'
                                }}
                            ></div>
                        </div>
                        <div
                            style={{
                                width: stepShow ? 280 : 0,
                                opacity: stepShow ? 1 : 0,
                                maxHeight: stepShow ? 99999 : 0,
                                overflow: stepShow ? 'initial' : 'hidden',
                                transition: 'all 0.8s ',
                                flex: 'none',
                                marginTop: 39,
                                paddingTop: 20,
                                borderTop: '1px solid rgb(232, 232, 232)'
                            }}
                        >
                            <TalentStatusStep
                                talentId={resumeId}
                                refresh={getRefreshByKey('TalentStatusStep')}
                                onRefreshed={() => removeRefreshedComponent('TalentStatusStep')}
                            />
                        </div>
                    </Row>
                </div>
            </PageContainer>
        </TalentDetailContext.Provider>
    );
};
export default connect(({ user }) => ({ user }))(TalentDetail);
